package com.mysqltest.servlet;


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MysqlJDBC extends HttpServlet {

	private static final long serialVersionUID = 8130131809135818689L;

	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String driver="com.mysql.jdbc.Driver";
   		String url="jdbc:mysql://localhost/test_web";
   		String username="dong";
   		String password="xiaodong";
   		String sql="select * from jsp14_role where id=?";
   		Connection conn;
   		ResultSet rs=null;
//   		System.out.println("id="+req.getParameter("id"));
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url,username,password);
			PreparedStatement psd=conn.prepareStatement(sql);
			psd.setInt(1,Integer.parseInt(req.getParameter("id")));
			rs=psd.executeQuery();
			String name=null;
			while(rs.next()){
				name=rs.getString("name");
			}
			req.setAttribute("name",name);
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
			System.out.println("连接成功");
			rs.close();
			psd.close();
			conn.close();
		} catch (SQLException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		} catch (InstantiationException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			System.out.println("连接失败");
			e.printStackTrace();
		}
   		
	}
	
	
	
}
